<?php

/**
 * This class handles image rendering. It works with the generic images_table in the database, if
 * no image can be found or created then an error image is returned instead
 *
 * @author David Morris
 */
class Image extends CI_Controller {
    
    
    private $Width, $Height, $MimeType, $Source;
    
    
    /**
     * Renders an image via it's database ID. We search the database for that image's details
     * and render the appropriate image (Original, thumbnail, resized image)
     * 
     * @param int $imageId
     * @param bool $thumb
     * @param int $newWidth
     * @param int $newHeight 
     */
    function render($imageId,$thumb = false, $newWidth = 0, $newHeight = 0)
    {   
        $this->load->database();
        $Image = $this->db->query("SELECT * FROM images_table WHERE image_id = ?",array($imageId))->result();
        // If the image doesn't exist in the databse, error
        if(!count($Image))
            $this->error("Image does not exist in the database");       
        $Image = $Image[0];        
        $this->MimeType = image_type_to_mime_type($Image->image_type);
        $this->Width = $Image->image_width;
        $this->Height = $Image->image_height;
        $this->Source = $Image->image_location; 
        
        // Annoyingly, $thumb is cast to string and even if it says "false" it is still treated as true.
        if($thumb !== 'false')
            $this->Source = $Image->image_thumb;
        
        // If we are resizing the image, check the new widths and heights
        if($newHeight > 0 && $newWidth > 0 && ($newHeight !== $this->Height 
                || $newWidth !== $this->Width))
        {
            $this->Width = $newWidth;
            $this->Height = $newHeight;
            $Config = array(
                'source_image' => $this->Source,
                'width' => $this->Width,
                'height' => $this->Height,
                'maintain_ratio' => TRUE,
                'dynamic_output' => TRUE
            );
            $this->load->library('image_lib', $Config);
            if(!$this->image_lib->resize())
                $this->error($this->image_lib->display_errors('',"\n"));
            
        }
        else    // If we're just displaying what's on the file system
        {
            if(!file_exists($this->Source))
                $this->error('This file does not exist!');
            $this->output->set_content_type($this->MimeType)->set_output(file_get_contents($this->Source)); 
        }
        
    }
    
    /**
     * Creates a new image with our error message in it.
     * The image is going to be the size it needs to be to fit the error messages or
     * it will be the size of the intended image, which ever is bigger. That way if the
     * original image was big, but the error image is small, this won't compromise the
     * front end design.
     * 
     * @param string $message The error message, new lines should be split \n
     */
    function error($message)
    {
        
        $message = explode("\n", $message);
	$numLines = count($message);
	$maxLen = 0;
        
        //Get font sizes and work out the size or image needs to be.
	foreach($message as $msg)
		$maxLen = max($maxLen, strlen($msg));
	
	$fontMultiplier = 3;
	$fontWidth = imagefontwidth($fontMultiplier);
	$fontHeight = imagefontheight($fontMultiplier);
	
	$width = max($this->Width,(20 + $fontWidth * $maxLen));
	$height = max($this->Height,(20 + $fontHeight * $numLines));
	
        // Create a black canvas
	$canvas = imagecreate($width, $height);
        // Set our background colour
	$background = imagecolorallocate($canvas, 255, 255, 255);
        // Set our border colour
        $border = imagecolorallocate($canvas, 0, 0, 0);
        // Set the font colour
	$fontColour = imagecolorallocate($canvas, 255, 0, 0);
        // Fill the background
	imagefilledrectangle($canvas, 0, 0, $width, $height, $background);
        // Create a border 1px in
	imagerectangle($canvas, 0, 0, $width - 1, $height - 1, $border);
	
        // Foreach of the error lines, put them on a new line
	for($i = 0; $i < $numLines; $i++)
		imagestring($canvas, $fontMultiplier, 10, 10 + $i * $fontHeight, $message[$i], $fontColour);
        // Set the header to be png, display the image and die
        header('Content-Type: image/png');
        die(imagepng($canvas));
    }

    
    
}

?>
